"""
author:俞婧，田新宇,杨光
create time:2020-07-07
update time:2020-07-21
"""

from django.shortcuts import render,redirect
from .models import User,course_user,course
# from course.models import Course
from .forms import UserForm,RegisterForm,FindpwdForm

from django.forms.models import model_to_dict
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import re
import rsa
from binascii import b2a_hex, a2b_hex
# Create your views here.
def index(request):
    '''显示首页'''
    return render(request,'login/index.html')

def login(request):
    if request.session.get('is_login',None):#不允许重复登录
        return redirect('/index')
    if request.method == "POST":
        login_form = UserForm(request.POST)
        message = "请检查填写的内容！"
        if login_form.is_valid():#用户名和密码不能为空
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            try:
                user = User.objects.get(name=username)
                if decrypt(user.password).decode() == password:
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name
                    return redirect('index/')
                else:
                    message = "密码错误！"
            except:
                message = "用户名不存在！"
        return render(request,'login/login.html',locals())

    login_form = UserForm()
    return render(request,'login/login.html',locals())

def register(request):
    if request.session.get('is_login', None):
        # 登录状态不允许注册。你可以修改这条原则！
        return redirect("/index/")
    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        message = "请检查填写的内容！"
        if register_form.is_valid():  # 获取数据
            username = register_form.cleaned_data['username']
            password1 = register_form.cleaned_data['password1']
            password2 = register_form.cleaned_data['password2']
            email = register_form.cleaned_data['email']

            #校验邮箱,正则校验
            # if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
            #     return render(request,'login/register.html',{'errmsg':'邮箱格式错误'})

            if password1 != password2:  # 判断两次密码是否相同
                message = "两次输入的密码不同！"
                return render(request, 'login/register.html', locals())
            else:
                same_name_user = User.objects.filter(name=username)
                if same_name_user:  # 用户名唯一
                    message = '用户已经存在，请重新选择用户名！'
                    return render(request, 'login/register.html', locals())
                same_email_user = User.objects.filter(email=email)
                if same_email_user:  # 邮箱地址唯一
                    message = '该邮箱地址已被注册，请使用别的邮箱！'
                    return render(request, 'login/register.html', locals())

                # 当一切都OK的情况下，创建新用户
                new_user = User.objects.create() # django内置的创建用户函数
                new_user.name = username
                new_user.password = encrypt(password1).decode()
                new_user.email = email
                new_user.save()#保存到数据库
                return redirect('/login/')  # 自动跳转到登录页面
    register_form = RegisterForm()
    return render(request, 'login/register.html', locals())

def logout(request):
    if not request.session.get('is_login',None):
        #如果本来就未登录，就没有登出
        return redirect("/index/")
    request.session.flush()
    return redirect('/login/')   #index

def user_center(request):
    user_info=User.objects.get(id=request.session['user_id'])
    courses = course_user.objects.filter(user_id=user_info)
    list_course = []
    for co in courses:
        collections = {}
        collections['id'] = co.course.id
        collections['course_name'] = co.course.course_name
        collections['school'] = co.course.course_school
        collections['teacher'] = co.course.course_teacher
        collections['status'] = co.course.course_status
        collections['type'] = co.course.course_type
        collections['time'] = co.course.course_time
        collections['credit'] = co.course.course_credit
        list_course.append(collections)

    context = {
        'nick_name': user_info.nick_name,
        'email': user_info.email,
        'sign': user_info.sign,
        'course_obj': list_course
    }
    return render(request,'login/user_center.html',context=context)
#选课
def show_course(request):
    courseStudent = request.session['user_id']
    courses=course_user.objects.filter(user_id=courseStudent)
    list_course=[]
    for co in courses:
        collections={}
        collections['id'] = co.course.id
        collections['course_name']=co.course.course_name
        collections['school'] = co.course.course_school
        collections['teacher'] = co.course.course_teacher
        collections['status'] = co.course.course_status
        collections['type'] = co.course.course_type
        collections['time'] = co.course.course_time
        collections['credit'] = co.course.course_credit
        list_course.append(collections)
    return render(request,'login/user_center.html',{'course_obj':list_course})


@csrf_exempt
def edit_user(request):
    if request.method=="POST":
        # password = reuqest.POST.get('password')
        sign = request.POST.get('sign')
        nick_name = request.POST.get('nick_name')
       # email = request.POST.get('email')
        User.objects.filter(id=request.session['user_id']).update(sign=sign,nick_name=nick_name)
        return redirect('/user_center/')

def del_course(request):
    id=request.GET.get('id')
    course_user.objects.filter(course_id=id).delete()
    return redirect('/show_course/')

pubkey, prikey = rsa.newkeys(256)
def encrypt(text):
    ciphertext = rsa.encrypt(text.encode(),pubkey)
    return b2a_hex(ciphertext)
def decrypt(text):
    decrypt_text = rsa.decrypt(a2b_hex(text),prikey)
    return decrypt_text

def findpwd(request):
    # if request.session.get('is_login',None):#不允许重复登录
    #     return redirect('/index')
    if request.method == "GET":
        findpwd_form = FindpwdForm(request.GET)
        if findpwd_form.is_valid():  # 获取数据
            username = findpwd_form.cleaned_data['username']
            email = findpwd_form.cleaned_data['email']

            same_name_user = User.objects.filter(name=username)
            same_email_user = User.objects.filter(email=email)

            user = User.objects.get(name=username)
            if same_email_user & same_name_user:
                code = decrypt(user.password).decode()
                message = '密码是'+code
                return render(request,'login/findpwd.html',locals())
    return render(request,'login/findpwd.html',locals())